import { CookieStorage } from "cookie-storage";
const cookieStorage = new CookieStorage();

// 随机长度字符串
const randomString = (len) => {
  len = len || 10;
  var chars = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
  var maxPos = chars.length;
  var str = "";
  for (let i = 0; i < len; i++) {
    str += chars.charAt(Math.floor(Math.random() * maxPos));
  }
  return str;
};

// 设置localStorage
const _setItem = (key, data) => {
  localStorage.setItem(key, JSON.stringify(data));
};

// 获取localStorage
const _getItem = (key) => {
  let data = localStorage.getItem(key);
  if (data) data = JSON.parse(data);
  return data;
};

// 删除localStorage
const _removeItem = (key) => {
  localStorage.removeItem(key);
};

// 缓存用户信息
const setUserInfoCache = (info) => {
  _setItem("__UserInfo__", info);
};

// 获取缓存的用户信息
const getUserInfoCache = () => {
  let data = _getItem("__UserInfo__");
  return data;
};

// 删除用户信息
const removeUserInfoCache = () => {
  _removeItem("__UserInfo__");
};

// 缓存token
const setToken = (value) => {
  let curDate = new Date();
  let nextDate = new Date(curDate.getTime() + 24 * 60 * 60 * 1000);

  cookieStorage.setItem("Authorization", value, {
    domain: document.domain,
    expires: nextDate,
  });
};

// 获取token
const getToken = () => {
  return cookieStorage.getItem("Authorization");
};

// 删除token
const removeToken = () => {
  cookieStorage.removeItem("Authorization");
};

export {
  randomString,
  setUserInfoCache,
  getUserInfoCache,
  removeUserInfoCache,
  setToken,
  getToken,
  removeToken,
};
